package controllers

import (
	"mailsrv/models"
	"github.com/astaxie/beego"
	"encoding/json"
)

var(
	mailQueue = make(chan models.MailBody, 10)
)

type ApiController struct {
	BaseController
}

func init(){
	beego.Notice("##并行的方式开启邮件发送服务##")
	go func(){
		for {
			select {
			case mailbb := <-mailQueue:
				mailbb.SingleMailTo()

			}
		}
	}()
}


func (this *ApiController) Prepare() {
	//先执行
	this.BaseController.Prepare()
	content := this.Ctx.Input.RequestBody
	apiSign := models.ApiSign{}
	json.Unmarshal(content, &apiSign)

	err := apiSign.CheckSign()
	if err != nil{
		this.ajaxReturn("", err.Error(), 400)
	}
}

func (this *ApiController) SendOne(){
	content := this.Ctx.Input.RequestBody
	mailbb := models.MailBody{}
	json.Unmarshal(content, &mailbb)

	id,err := mailbb.SendOne()

	if err != nil{
		this.Ctx.WriteString(err.Error())
		this.StopRun()
	}
	mailbb.Id = id
	mailQueue<-mailbb

	this.ajaxReturn("", "push a new mail", 200)
}